<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/12/17
 * Time: 22:21
 */

namespace app\common\model;

use think\Cache;

class MonthFortune extends Base
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_month_fortune';

    public function getMonthFortune($map = [])
    {
        if (empty($map) || !isset($map['rid']) || !isset($map['month']))
        {
            return [];
        }
        $data = false;

        if(strlen($map['month']) === 6)
        {
            $map['month'] = str_replace('-','-0',$map['month']);
        }

        if ($this->cache_on >= 1)
        {
            $data = Cache::get('fortune_month_' . $map['rid'] . '_' . $map['month']);
        }
        if ($data === false)
        {
            try
            {
                $data = $this->where(['rid' => $map['rid'], 'month' => $map['month']])->findOrFail()->toArray();

                // redis 字符串直接存入redis
                $data = $data['fortune'];

                Cache::set('fortune_month_' . $map['rid'] . '_' . $map['month'], $data, 86400 * 7);
            }
            catch (\Exception $e)
            {
                $data = '';
            }
        }
        return $data;
    }

    public function addFortune($insertData = [])
    {
        $status = true;
        if (empty($insertData))
        {
            return false;
        }
        try
        {
            // 先删除，后添加
            $this->where(['rid' => $insertData['rid'], 'month' => $insertData['month']])->delete();

            $this->insertGetId($insertData);
        }
        catch (\Exception $e)
        {
            $status = false;
            \think\Log::write('月运势写入数据库失败：' . $e->getMessage(), 'error', true);
            \think\Log::write('数据：' . var_export($insertData,true), 'error', true);

        }
        return $status;
    }

    public function addFortuneForYear($insertData = [],$map = [])
    {
        $status = true;
        if (empty($insertData))
        {
            return false;
        }
        try
        {
            // 先删除，后添加 rid=>$rid,month in ('2018-01',2,3,4,5,6,7,8,9,10,11,12)
            $this->where($map)->delete();
            // 年运入库的时候，批量入库
            $this->insertAll($insertData);
        }
        catch (\Exception $e)
        {
            $status = false;
            print('年运-月运势写入数据库失败：' . $e->getMessage() . PHP_EOL);
            \think\Log::write('年运-月运势写入数据库失败：' . $e->getMessage(), 'error', true);
            \think\Log::write('数据：' . var_export($insertData,true), 'error', true);
        }
        return $status;
    }
}
